﻿using Mapster;
using Microsoft.VisualBasic;
using Prism.Commands;
using Prism.Services.Dialogs;
using SmartPlant.Core;
using SmartPlant.Core.Mvvm;
using SmartPlant.Model.Biz;
using SmartPlant.Services;
using SmartPlant.WinCore;
using System.Collections.ObjectModel;
using System.Drawing;
using System.Windows.Input;
using Telerik.Windows.Controls;
using Unity;

namespace SmartPlant.Modules.Base.ViewModels
{
    public class CodelistEditViewModel : DialogViewModelBase, IDialogAware
    {


        public CodelistEditViewModel(IDialogService dialogService, IUnityContainer unityContainer) : base(dialogService)
        {
            _codelistServ = unityContainer.Resolve<CodeListService>();
            TableData = new ObservableCollection<DropDownListObj>();
        }
        /// <summary>
        /// 当前处理的id
        /// </summary>
        private string DATATYPE;
        private CodeListService _codelistServ;
        private ObservableCollection<DropDownListObj> _TableData;
        private DelegateCommand<object> _DeleteDialogCommand;
        private DelegateCommand<object> _AddDialogCommand;
        /// <summary>
        /// 请求dialog时，就用nameof(XXX) 作为参数 带进来
        /// </summary>
        private string type;
        private DelegateCommand<object> _CellEditEndedCommand;
        private DropDownListObj _selectedRow;
        #region binding-data

        public DropDownListObj selectedRow
        {
            get
            {
                return _selectedRow;
            }
            set
            {
                SetProperty(ref _selectedRow, value);

            }
        }
        /// <summary>
        /// 列表
        /// </summary>
        public ObservableCollection<DropDownListObj> TableData
        {
            get
            {
                return _TableData;
            }
            set
            {
                SetProperty(ref _TableData, value);
            }

        }

        /// <summary>
        /// 删除按钮 绑定
        /// </summary>
        public ICommand DeleteDialogCommand
        {
            get
            {
                if (_DeleteDialogCommand != null) return _DeleteDialogCommand;
                _DeleteDialogCommand = new DelegateCommand<object>(onDeleteDialogCommand);
                return _DeleteDialogCommand;
            }
        }

        /// <summary>
        /// 新增按钮 绑定
        /// </summary>
        public ICommand AddDialogCommand
        {
            get
            {
                if (_AddDialogCommand != null) return _AddDialogCommand;
                _AddDialogCommand = new DelegateCommand<object>(onAddDialogCommand);
                return _AddDialogCommand;
            }
        }
        public ICommand CellEditEndedCommand
        {
            get
            {
                if (_CellEditEndedCommand != null)
                {
                    return _CellEditEndedCommand;
                }
                _CellEditEndedCommand = new DelegateCommand<object>(OnCellEditEndedCommandAsync);
                return _CellEditEndedCommand;
            }
        }

        #endregion
        private void onAddDialogCommand(object obj)
        {
            if (TableData.Any(x => x.Id == "新增" && string.IsNullOrEmpty(x.Name)))
            {
                Dialog.ShowAltert("上一个新增记录不能为空");

            }
            else
            {
                var newItem = new DropDownListObj() { Id = "新增", isModified = true };
                TableData.Add(newItem);
                selectedRow = newItem;
            }

        }
        private void onDeleteDialogCommand(object obj)
        {
            if (selectedRow == null)
            {
                //    Dialog.ShowMessage("空行");
                return;
            }
            Dialog.ShowQuestion("此删除操作是不可逆的，是否确认？", (p) =>
            {
                switch (p?.Result)
                {

                    case ButtonResult.OK:
                    case ButtonResult.Yes:

                        var res = Task.Run(async () => await _codelistServ.DelCodelist(type, selectedRow.Id));
                        if (res.Result)
                        {
                            TableData.Remove(selectedRow);
                        }


                        //var res2 = _codelistServ.DelCodelist2(type, selectedRow.Id);

                        break;
                    default:
                        return;
                }

            });
        }

        /// <summary>
        /// 关闭窗口后。xaml绑定的是 <see cref="DialogViewModelBase.CloseDialogCommand"/>
        /// </summary>
        /// <returns></returns>
        protected override DialogResult RaiseDialogOk()
        {
            //关闭时，处理增和改 
            foreach (var item in TableData.Where(x => x.isModified))
            {
                if (item.Id == "新增")
                {
                    var task = Task.Run(async () => await _codelistServ.AddCodeList(type, item));
                    task.Wait();
                }
                else
                {
                    //改
                    var task2 = Task.Run(async () => await _codelistServ.UpdateCodelist(type, item));
                    task2.Wait();
                }
                item.isModified = false;
            }


            var task3 = Task.Run(async () => await _codelistServ.GetDropDownListByDefAsync(DATATYPE, "lookup", true));


            task3.Wait();


            return new DialogResult(ButtonResult.OK);
        }
        public string test()
        {
            return "xx";
        }
        public async Task<string> test2()
        {
            await Task.Run(() => { });
            return "xx";
        }
        /// <summary>
        /// 单元格编辑结束的处理命令
        /// </summary>
        /// <param name="obj"></param>
        void OnCellEditEndedCommandAsync(object obj)
        {
            var e = obj as GridViewCellEditEndedEventArgs;
            if (e == null) return;
            var enumObj = e.Cell.DataContext;
            if (enumObj == null)
            {
                return;
            }
            var enumObj2 = (DropDownListObj)enumObj;
            enumObj2.isModified = true;
            //if (dropVal != null)
            //{
            //    return;
            //}
            //else
            //{
            //    var pRow = e.Cell.ParentRow.DataContext;
            //    Reflect.SetPropValue(pRow, tag.v1, e.OldData);
            //    return;
            //}
        }
        /// <summary>
        /// 对话框打开时，触发。由prism的dialog机制来决定
        /// </summary>
        /// <param name="parameters"></param>
        public override async void OnDialogOpened(IDialogParameters parameters)
        {
            DATATYPE = parameters.GetValue<string>(DialogParameterKeys.Id);//L1084
            Title = parameters.GetValue<string>(DialogParameterKeys.Title);
            type = parameters.GetValue<string>(DialogParameterKeys.Purpose);//
            var list = await _codelistServ.GetDropDownListByDefAsync(DATATYPE);//所以改了之后全局都会改
            if (list != null)
            {
                TableData.Clear();
                TableData.AddRange(list);

            }
        }
    }
}
